/* ----------------------------------------------------------------------------
 * Copyright (c) Huawei Technologies Co., Ltd. 2013-2019. All rights reserved.
 * Description: Sem Debug
 * Author: huangjieliang
 * Create: 2013-01-01
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific prior written
 * permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * --------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------------
 * Notice of Export Control Law
 * ===============================================
 * Huawei LiteOS may be subject to applicable export control laws and regulations, which might
 * include those applicable to Huawei LiteOS of U.S. and the country in which you are located.
 * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such
 * applicable export control laws and regulations.
 * --------------------------------------------------------------------------- */
#include "los_config.h"
#include "los_typedef.h"
#include "los_task_pri.h"
#include "los_sem_pri.h"

#ifdef LOSCFG_SHELL
#include "string.h"
#include "stdlib.h"
#include "shcmd.h"
#endif

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* __cplusplus */

#ifdef LOSCFG_DEBUG_SEMAPHORE
typedef struct {
    UINT16  origSemCount;   /**< Number of orignal available semaphores */
    UINT64  lastAccessTime; /**< The last operation time                 */
    VOID    *creater;       /**< The task entry who created this sem     */
} SemDebugCB;

static SemDebugCB *g_semDebugArray;

/* This sort function is modified from MUX. */
static VOID osArraySortByTime(UINT32 *sortArray, UINT32 start, UINT32 end)
{
    UINT32 left = start;
    UINT32 right = end;
    UINT32 idx = start;
    UINT32 pivot = sortArray[start];

    while (left < right) {
        while (left < right &&
               g_semDebugArray[sortArray[right]].lastAccessTime > g_semDebugArray[pivot].lastAccessTime) {
            right--;
        }

        if (left < right) {
            sortArray[left] = sortArray[right];
            idx = right;
            left++;
        }

        while (left < right &&
               g_semDebugArray[sortArray[right]].lastAccessTime < g_semDebugArray[pivot].lastAccessTime) {
            left++;
        }

        if (left < right) {
            sortArray[right] = sortArray[left];
            idx = left;
            right--;
        }
    }

    sortArray[idx] = pivot;

    if (start < idx) {
        osArraySortByTime(sortArray, start, idx - 1);
    }
    if (idx < end) {
        osArraySortByTime(sortArray, idx + 1, end);
    }
}

VOID osSemDbgInit(VOID)
{
    g_semDebugArray = (SemDebugCB *)LOS_MemAlloc(m_aucSysMem0, LOSCFG_BASE_IPC_SEM_LIMIT * sizeof(SemDebugCB));
    if (g_semDebugArray == NULL) {
        PRINT_ERR("%s: malloc failed!\n", __FUNCTION__);
    }
    return;
}

VOID osSemDbgTimeUpdate(UINT32 semID)
{
    SemDebugCB *semDebug = &g_semDebugArray[GET_SEMINDEX(semID)];
    semDebug->lastAccessTime = LOS_TickCountGet();
    return;
}

VOID osSemDbgUpdate(UINT32 semID, VOID *creater, UINT16 count)
{
    SemDebugCB *semDebug = &g_semDebugArray[GET_SEMINDEX(semID)];
    semDebug->creater = creater;
    semDebug->lastAccessTime = LOS_TickCountGet();
    semDebug->origSemCount = count;
    return;
}

UINT32 osSemInfoGetFullData(VOID)
{
    UINT32 usedSemCnt = 0;
    UINT32 firstNode = 1;
    LosSemCB *semNode = (LosSemCB *)NULL;
    LosTaskCB *tskCB = (LosTaskCB *)NULL;
    SemDebugCB *semDebug = (SemDebugCB *)NULL;
    UINTPTR intSave;
    UINT32 i;
    UINT32 *semIndexArray = NULL;
    UINT32 count;

    /* Get the used semaphore count. */
    for (i = 0; i < LOSCFG_BASE_IPC_SEM_LIMIT; i++) {
        semNode = GET_SEM(i);
        semDebug = &g_semDebugArray[i];
        if (semNode->semStat == OS_SEM_USED && semDebug->creater != NULL) {
            usedSemCnt++;
        }
    }

    if (usedSemCnt > 0) {
        semIndexArray = (UINT32 *)LOS_MemAlloc((void *)OS_SYS_MEM_ADDR, usedSemCnt * sizeof(UINT32));
        if (semIndexArray == NULL) {
            PRINTK("LOS_MemAlloc failed in %s \n", __func__);
            return LOS_NOK;
        }

        /* Fill the semIndexArray with the real index. */
        count = 0;
        for (i = 0; i < LOSCFG_BASE_IPC_SEM_LIMIT; i++) {
            semNode = GET_SEM(i);
            semDebug = &g_semDebugArray[i];
            if (semNode->semStat == OS_SEM_USED && semDebug->creater != NULL) {
                *(semIndexArray + count) = i;
                count++;
                /* if the count is touched usedSemCnt break. */
                if (count >= usedSemCnt) {
                    break;
                }
            }
        }

        /* It will Print out ALL the Used Semaphore List. */
        PRINTK("Used Semaphore List: \n");
        PRINTK("\r\n   SemID    Count    OriginalCount   Creater(TaskEntry)    LastAccessTime\n");
        PRINTK("   ------   ------   -------------   ------------------    --------------   \n");

        /* Sort this index array. */
        osArraySortByTime(semIndexArray, 0, usedSemCnt - 1);
        for (i = 0; i < usedSemCnt; i++) {
            semNode = GET_SEM(semIndexArray[i]);
            semDebug = &g_semDebugArray[semIndexArray[i]];

            PRINTK("   0x%-07x0x%-07u0x%-14u%-22p0x%llx\n", semNode->semID, semDebug->origSemCount,
                   semNode->semCount, semDebug->creater, semDebug->lastAccessTime);
            if (!LOS_ListEmpty(&semNode->semList)) {
                PRINTK("Pended task list : ");
                intSave = LOS_IntLock();
                LOS_DL_LIST_FOR_EACH_ENTRY(tskCB, &semNode->semList, LosTaskCB, pendList)
                {
                    if (firstNode) {
                        PRINTK("%s", tskCB->taskName);
                        firstNode = 0;
                    } else {
                        PRINTK(", %s", tskCB->taskName);
                    }
                }
                LOS_IntRestore(intSave);
                PRINTK("\n");
            }
        }

        /* free the index array. */
        LOS_MemFree((void *)OS_SYS_MEM_ADDR, semIndexArray);
    }
    return LOS_OK;
}
#endif /* LOSCFG_DEBUG_SEMAPHORE */

#ifdef LOSCFG_SHELL
LITE_OS_SEC_TEXT_MINOR UINT32 osShellCmdSemInfoGet(UINT32 argc, CHAR **argv)
{
    UINT32 loop;
    UINT32 semCnt = 0;
    UINTPTR intSave;
    UINT32 firstNode = 1;
    LosTaskCB *tskCB = (LosTaskCB *)NULL;
    LosSemCB *semNode = (LosSemCB *)NULL;
    UINT32 ret = LOS_OK;
    UINT32 semID;
    CHAR *endPtr = (CHAR *)NULL;

    if (argc > 1) {
#ifdef LOSCFG_DEBUG_SEMAPHORE
        PRINTK("\nUsage: sem [fulldata|ID]\n");
#else
        PRINTK("\nUsage: sem [ID]\n");
#endif
        return OS_ERROR;
    }

    if (argc == 0) {
        semID = 0xffffffff;
    } else {
#ifdef LOSCFG_DEBUG_SEMAPHORE
        if (strcmp(argv[0], "fulldata") == 0) {
            ret = osSemInfoGetFullData();
            return ret;
        }
#endif
        semID = (UINT32)strtoul(argv[0], &endPtr, 0);
        if (endPtr == (CHAR *)NULL || *endPtr != 0 || (INT32)semID < 0) {
            PRINTK("\nsem ID can't access %s.\n", argv[0]);
            return 0;
        }
    }

    if (semID == 0xffffffff) {
        for (loop = 0; loop < LOSCFG_BASE_IPC_SEM_LIMIT; loop++) {
            semNode = GET_SEM(loop);
            if (semNode->semStat == OS_SEM_USED) {
                semCnt++;
                PRINTK("\r\n   SemID       Count\n");
                PRINTK("   ----------  -----\n");
                PRINTK("   0x%08x  %u\n", semNode->semID, semNode->semCount);
            }
        }
        PRINTK("   SemUsingNum    :  %d\n\n", semCnt);
        return ret;
    } else {
        if (GET_SEMINDEX(semID) >= LOSCFG_BASE_IPC_SEM_LIMIT) {
            PRINTK("\nInvalid semphore id!\n");
            return ret;
        }

        semNode = GET_SEM(semID);

        if (semNode->semID != semID || semNode->semStat != OS_SEM_USED) {
            PRINTK("\nThe semphore is not in use!\n");
            return ret;
        }

        PRINTK("\r\n   SemID       Count\n");
        PRINTK("   ----------  -----\n");
        PRINTK("   0x%08x      0x%u\n", semNode->semID, semNode->semCount);

        if (LOS_ListEmpty(&semNode->semList)) {
            PRINTK("No task is pended on this semphore!\n");
            return ret;
        } else {
            PRINTK("Pended task list : ");

            intSave = LOS_IntLock();

            LOS_DL_LIST_FOR_EACH_ENTRY(tskCB, &semNode->semList, LosTaskCB, pendList)
            {
                if (firstNode) {
                    PRINTK("%s", tskCB->taskName);
                    firstNode = 0;
                } else {
                    PRINTK(", %s", tskCB->taskName);
                }
            }
            LOS_IntRestore(intSave);
            PRINTK("\n");
        }
    }

    return LOS_OK;
}

SHELLCMD_ENTRY(sem_shellcmd, CMD_TYPE_EX, "sem", 1, (CMD_CBK_FUNC)osShellCmdSemInfoGet); /*lint !e19*/
#endif

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */

